package com.zmx.aop;

import com.alibaba.fastjson.JSON;
import com.zmx.entity.SysLog;
import com.zmx.entity.SysUser;
import com.zmx.service.SysLogService;
import com.zmx.utils.HttpContextUtils;
import com.zmx.utils.IPUtils;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * 2020/10/22
 * 11:08
 * zmx
 */
@Component
@Aspect
public class MyLogAspect {
    @Resource
    SysLogService sysLogService;


    @After("myPointCut()")
    public void after(JoinPoint joinPoint){
        Class<?> targetClass = joinPoint.getTarget().getClass();
        Object[] args = joinPoint.getArgs();
        // 获得方法参数
        String params = JSON.toJSONString(args);
        // 获得方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String description= null;
        // 获得注解信息
        if (method.isAnnotationPresent(MyLog.class)){
            MyLog myLog = method.getAnnotation(MyLog.class);

            description = myLog.description();
            if (description == null||description.equals("")) {
                description=myLog.value();
            }
        }
        // ip地址
        String ip = IPUtils.getIpAddr(HttpContextUtils.getHttpServletRequest());
        // 用户名
        SysUser principal = (SysUser) SecurityUtils.getSubject().getPrincipal();
        String username = principal.getUsername();

        String methodName = targetClass.getName()+method.getName();
        SysLog sysLog =new SysLog(0L,username,description,methodName,params,ip,new Date());
       sysLogService.insertLog(sysLog);

    }
}
